package com.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: 一个小菜逼
 * @Date: 2020/4/16
 */
public class MyHttpClient {
    public static void main(String[] args) {
        String url="http://192.168.1.102:8848";
        try {
            String hello_world = sendPost(url, "hello world");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String sendPost(String url, String Params) throws IOException {
        //url="http://192.168.1.102/client";
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        String response = "";
        try {
            URL httpUrl = null; //HTTP URL类 用这个类来创建连接
            //创建URL
            httpUrl = new URL(url);
            //建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            //客户端的请求方式
            conn.setRequestMethod("POST");
            //客户端发送的数据类型
            conn.setRequestProperty("Content-Type", "application/json");
            //设置长连接
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);//设置不要缓存
            conn.setInstanceFollowRedirects(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //进行连接
            conn.connect();
            //得到连接的输出流
            out = new OutputStreamWriter(
                    conn.getOutputStream());
            //将参数写入输出流
            out.write(Params);
            //刷新输出流,应该是将输出流中的数据推送出去
            out.flush();
            System.out.println("正在阻塞："+Thread.currentThread().getName());
            //线程应该是阻塞在这等待服务端的响应
            //将服务器端返回的字节流转换为字符流
            reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            System.out.println("解除阻塞"+Thread.currentThread().getName());
            String lines;
            //将字符流转换为字符串
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                response += lines;
            }
            System.out.println("服务器端返回的消息为："+response);
            //关闭字符缓冲区
            reader.close();
            // 断开连接
            conn.disconnect();

            // log.info(response.toString());
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！");
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return response;
    }
}
